package Linux五种IO模型;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author coderFu
 * @create 2022/3/5
 * 手写BIO ，同步非阻塞IO
 */
public class BIOServer {

    public static void main(String[] args) {

        try(ServerSocket serverSocket = new ServerSocket(8081)){
            System.out.println("服务端端口号："+serverSocket.getLocalSocketAddress());

            // 不断的接收客户端的请求
            while(true){
                Socket clientSocket = serverSocket.accept();
                System.out.println("链接来自："+clientSocket.getRemoteSocketAddress());
                // 文件读写是否结束,查看是否有数据出来，无限循环
                try(Scanner input = new Scanner(clientSocket.getInputStream())) {
                    while(true){
                        String request = input.nextLine();
                        if ("quit".equals(request)){
                            System.out.println("客户端结束传输！");
                            break;
                        }
                        System.out.println("客户端端口"+clientSocket.getLocalSocketAddress());
                        System.out.println("客户端输入:"+request);
                        String response = "886："+request;
                        clientSocket.getOutputStream().write(response.getBytes());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
